#include <stdio.h>
#include <unistd.h>
#include <string.h>
//socket需要的头文件
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main()
{
    //创建套接字
    int sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if(sockfd < 0)
    {
        perror("socket\n");
        return 0;
    }
    //绑定地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(28989);
    addr.sin_addr.s_addr = inet_addr("172.16.0.5");
    int ret = bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
    if(ret < 0)
    {
        perror("bind\n");
        return 0;
    }

    while(1)
    {
        //接受数据
        char buf[1024] = {0};
        struct sockaddr_in peer_addr;
        socklen_t len = sizeof(peer_addr);
        ssize_t st = recvfrom(sockfd,buf,sizeof(buf)-1,0,(struct sockaddr*)&peer_addr,&len);
        if(st < 0)
        {
            continue;
        }
        printf("recv msg \"%s\"from %s:%d\n",buf,inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port));
        //刷新数据
        memset(buf,'\0',sizeof(buf));
        //格式输出
        sprintf(buf,"欢迎客户机:%s,端口为:%d\n",inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port));
        //发送
        sendto(sockfd,buf,strlen(buf),0,(struct sockaddr*)&peer_addr,len);
    }
    close(sockfd);
    return 0;
}
